﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Threading;
using TraceLog;

namespace UniversalQin
{
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App : Application
    {
        /// <summary>
        /// 初始化一个<see cref="App"/>类型的新实例
        /// 全局异常
        /// </summary>
        public App()
        {
            //注册全局事件
            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
            DispatcherUnhandledException += App_DispatcherUnhandledException;
            TaskScheduler.UnobservedTaskException += TaskScheduler_UnobservedTaskException;
        }

        MainWindow? window;
        private static Mutex m_Mutex;
        protected void Application_Startup(object sender, StartupEventArgs e)
        {
            Trace.Listeners.Clear();  //清除系统监听器 (就是输出到Console的那个)
            Trace.Listeners.Add(new TraceLog.TraceLogListener("UniversalQin")); //添加MyTraceListener实例

            bool createdNew = false;
            string name = @"UniversalQin";
            try
            {
                m_Mutex = new Mutex(false, name, out createdNew);
            }
            catch (Exception exception)
            {
                
                Trace.Write(new TraceLogType(WriteLogType.error, "Application_Startup"), exception.ToString());
                //QinsInterfaceMax.Log4Net.LogHelper.WriteError(typeof(App), exception.ToString());
                //SetStartResult(exception.Message, m_StartFrom);
                Environment.Exit(1);
            }
            if (createdNew)
            {
                window = new MainWindow();
                window.Show();
            }
            else
            {
                MessageBox.Show("软件已经打开！");
                //SendMsg("亚马逊小助手", "KP");
                Environment.Exit(1);
            }
        }


        private void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs args)
        {
            const string msg = "主线程异常";
            try
            {
                if (args.ExceptionObject is Exception && Dispatcher != null)
                {
                    Dispatcher.Invoke(() =>
                    {
                        Exception ex = (Exception)args.ExceptionObject;
                        HandleException(msg, ex);
                    });
                }
            }
            catch (Exception ex)
            {
                HandleException(msg, ex);
            }
        }

        private void App_DispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs args)
        {
            const string msg = "子线程异常";
            try
            {
                HandleException(msg, args.Exception);
                args.Handled = true;
            }
            catch (Exception ex)
            {
                HandleException(msg, ex);
            }
        }

        private void TaskScheduler_UnobservedTaskException(object? sender, UnobservedTaskExceptionEventArgs args)
        {
            const string msg = "异步异常";
            try
            {
                HandleException(msg, args.Exception);
                args.SetObserved();
            }
            catch (Exception ex)
            {
                HandleException(msg, ex);
            }
        }

        private void HandleException(string msg, Exception ex)
        {
            MessageBox.Show(ex.Message, msg);
        }
    }
}
